const app = require("express")();
const port = 8980;

//视频爬虫
const video = require("../JS/router/videos");
//图片爬虫
const image = require("../JS/router/csy");
//登录注册
const login_register = require("../JS/router/login_register");
//购物
const shopping = require("../JS/router/shopping");
//聊天
const chat = require("../JS/router/chat");
//头像
const avatar = require("../JS/router/avatar");


//！！！接口路由,待开发
const plcs = require("./router/Side_menu");

// 跨域设置
app.all("*", (req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Content-Type", "text/html; charset=utf-8");
  next();
});

//!!接口路由,待开发
app.use(image);
app.use(login_register);
app.use(shopping);
app.use(video);
app.use(chat);
app.use(avatar);

//!!接口路由,待开发
app.use(plcs);
//接口链接
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});


const http = require('http');
const socketIo = require('socket.io');
const { log } = require("console");
const server = http.createServer(app);

const io = socketIo(server, {
  cors: '*',
  methods: ['GET', 'POST'],
  credentials: true
});

const users = {};
let rooms = {};
io.on('connection', (socket) => {
  // 处理登录事件
  socket.on('userjoin', (data) => {
    // 保存当前登录用户信息
    rooms[data] = socket.id;
    // 处理私聊消息事件
    socket.on('privateMessage', (messageData) => {
      // 获取目标用户的socket ID
      const targetUserId = messageData.to;
      // 发送消息给发送者
      socket.emit('pm', { data: messageData });
      // 发送消息给目标用户
      if (rooms[targetUserId]) {
        io.to(rooms[targetUserId]).emit('pm', { data: messageData });
      }
    });
  });


  // 群聊部分
  socket.on('userlogin', (data) => {
    users.avatar = data.avatar;
    users.name = data.name;
    users.id = data.id;
  });

  socket.on('chatmessage', (msg) => {
    const user = { name: users.name, avatar: users.avatar, id: users.id };
    io.emit('chatmessage', { user, msg });
  });

  // 断开连接
  socket.on('disconnect', () => {
    //遍历 rooms 字典，找到当前用户所在的房间，然后删除该房间
    for (let room in rooms) {
      if (rooms[room] === socket.id) {
        delete rooms[room];
        break;
      }
    }
  });
});


const PORT = process.env.PORT || 3000;
io.listen(3001)
server.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});